<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 2017/5/4
 * Time: 下午6:10
 */
class Pos extends Eloquent
{
    public static function refundOrder($device_en,$cashier_trade_no){
        $access_token = Pos::loadToken();
        $service = 'cashier.api.refund';
        $timestamp = time() * 1000;
        $data = array('cashier_trade_no' => $cashier_trade_no);
        $signData = array(
            'device_en' => $device_en,
            'access_token' => $access_token,
            'service' => $service,
            'timestamp' => $timestamp,
            'data' => json_encode($data)
        );

        $signature = Pos::Sign($signData);
        $signData['signature'] = $signature;

        $str = '';
        foreach ($signData as $key => $value) {
            $str .= $key . '=' . $value . '&';
        }
        $url = 'http://open.wangpos.com/wopengateway/api/entry?'.$str;
        $response = Pos::request($url);
        return $response;
    }

    //支付通知
    public static function notifyOrder($data){
        $sign = $data['sign'];

        /*验签规则不明，需要增加验签名的规则。*/
        $data = Pos::array_remove($data,'sign');
        $data = Pos::array_remove($data,'sign_type');
        $data = Pos::array_remove($data,'_url');
        $chackSign = Pos::Sign($data,'md5');

        if($sign == $chackSign){
            $result = 'success';
        }else{
            $result = 'fail';
        }
        Pos::saveLog(json_encode($data),'success');
        return WposRecord::notifyOrder($data);

        // return $result;
    }

    //订单状态
    public static function statusOrder($order_id){
        $access_token = Pos::loadToken();
        $service = 'cashier.api.query';
        $timestamp = time() * 1000;
        $signData = array(
            'out_trade_no' => $order_id,
            'access_token' => $access_token,
            'service' => $service,
            'timestamp' => $timestamp,
        );

        $signature = Pos::Sign($signData);
        $signData['signature'] = $signature;

        $str = '';
        foreach ($signData as $key => $value) {
            $str .= $key . '=' . $value . '&';
        }
        $url = 'http://open.wangpos.com/wopengateway/api/entry?'.$str;
        $response = Pos::request($url);
        return $response;

    }

    //推送状态
    public static function statusPush($seq_no){
        $access_token = Pos::loadToken();
        $service = 'base.msg.get_delivery_status';
        $timestamp = time() * 1000;
        $signData = array(
            'seq_no' => $seq_no,
            'access_token' => $access_token,
            'service' => $service,
            'timestamp' => $timestamp,
        );

        $signature = Pos::Sign($signData);
        $signData['signature'] = $signature;

        $str = '';
        foreach ($signData as $key => $value) {
            $str .= $key . '=' . $value . '&';
        }
        $url = 'http://open.wangpos.com/wopengateway/api/entry?'.$str;
        $response = Pos::request($url);
        return $response;

    }


    //下单
    public static function prepareOrder($device_en,$order_id,$amount,$desc,$attach,$pay_type=0,$call_scan=0){
        $notify_url = Config::get('pos.notify_url');
        $access_token = Pos::loadToken();
        $service = 'cashier.api.order';
        $timestamp = time() * 1000;
        $data = array(
            'out_trade_no' => $order_id, //订单ID
            'body' => $desc, //服务说明
            'total_fee' => $amount , //单位：分
            'notify_url' => Config::get('pos.notify_url') , //异步通知地址
            'attach' => $attach ,//附加信息
            'call_scan'=>$call_scan,//是否开启扫一扫 1 开始 0 不开启
        );
        if($pay_type!=0){
            $data["select_type"]=1;
            $data["pay_type"]=$pay_type;
        }   
        $signData = array(
            'device_en' => $device_en,
            'access_token' => $access_token,
            'service' => $service,
            'timestamp' => $timestamp,
            'data' => json_encode($data)
        );

        $signature = Pos::Sign($signData);
        $signData['signature'] = $signature;

        $str = '';
        foreach ($signData as $key => $value) {
            $str .= $key . '=' . $value . '&';
        }
        $url = 'http://open.wangpos.com/wopengateway/api/entry?'.$str;
        $response = Pos::request($url);
        return $response;
    }


    //获取银行流水
    public static function prepareFinance($ens,$startTime,$endTime,$accessToken,$pageIndex,$size){
        $method = 'facadeGetTransactionsList';
        $url = 'http://gw.api.wangpos.com/api/entry';
        $timestamp = date('Y-m-d H:i:s',time());
        $datas = array(
            'ens' => $ens, //设备号
            'startTime' => $startTime, //开始
            'endTime' => $endTime , //结束
            'vCode' => Config::get('pos.vCode') ,
            'accessToken' => $accessToken,
            'pageIndex'=>$pageIndex,
            'size'=>$size,
        );
        $datas = array(
            'datas'=>$datas
        );
        Log::debug(array('signData'=>json_encode($datas)));
        $signData = array(
            'access_token' => $accessToken,
            'method' => $method,
            'timestamp' => $timestamp,
            'open_param_json' => json_encode($datas),
            'vCode' => Config::get('pos.vCode')
        );
        Log::debug(array('signData'=>json_encode($signData)));
        $signature = Pos::financeSign($signData);
        $signData['signature'] = $signature;
        Log::debug(array('signData'=>json_encode($signData)));
        $str = '';
        foreach ($signData as $key => $value) {
            $str .= $key . '=' . $value . '&';
        }
//        $url .= '?' . $str;
        $response = Httpful::post($url)
            ->timeoutIn(5)
            ->body($signData)
            ->sendsForm()->send();
        Log::debug(array('response'=>$response));
        return $response->body;
    }

    //设备状态
    public static function statusDevice($device_en){
        $access_token = Pos::loadToken();
        $service = 'base.device.get_status';
        $timestamp = time() * 1000;

        $signData = array(
            'device_en' => $device_en,
            'access_token' => $access_token,
            'service' => $service,
            'timestamp' => $timestamp
        );

        $signature = Pos::Sign($signData);
        $signData['signature'] = $signature;

        $str = '';
        foreach ($signData as $key => $value) {
            $str .= $key . '=' . $value . '&';
        }
        $url = 'http://open.wangpos.com/wopengateway/api/entry?'.$str;
        $response = Pos::request($url);
        return $response;
    }
    //网络请求
    public static function request($url){
        $response = Httpful::get($url)
            ->timeoutIn(5)
            ->sendsForm()->send();

        Pos::saveLog($url,json_encode($response->body));
        return $response->body;
    }

    //记录日志
    public static function saveLog($request,$response){
        PosLogs::insert(array(
                'request' => $request,
                'response' => $response
            )
        );
    }
    //本地提取token
    public static function loadToken(){
        $token = PosToken::where('appid',Config::get('pos.appid'))->where('secret',Config::get('pos.secret'))->first();
        if(is_null($token)){
            $token_data = Pos::getToken();
        }else{
            if(time()*1000 > $token->expire_time){
                $token_data = Pos::getToken();
            }else{
                $token_data = $token->access_token;
            }
        }
        return $token_data;
    }

    //获取token
    public static function getToken(){
        $url = 'http://open.wangpos.com/wopengateway/api/accesstoken/get?appid='. Config::get('pos.appid') .'&secret='.Config::get('pos.secret');
        $token_data = Pos::request($url);

        if($token_data->status == 0){
            $count = PosToken::where('appid',Config::get('pos.appid'))->where('secret',Config::get('pos.secret'))->count();
            if($count > 0){
                PosToken::where('appid',Config::get('pos.appid'))
                    ->where('secret',Config::get('pos.secret'))
                    ->update(
                        array(
                            'access_token' => $token_data->data->access_token,
                            'expire_time' => $token_data->data->expire_time,
                        )
                    );
            }else{
                PosToken::insert(
                    array(
                        'appid' => Config::get('pos.appid'),
                        'secret' => Config::get('pos.secret'),
                        'access_token' => $token_data->data->access_token,
                        'expire_time' => $token_data->data->expire_time,
                    )
                );
            }
            return $token_data->data->access_token;
        }else{
            return $token_data->status;
        }
    }

    //获取Finance token
    public static function getFinanceToken(){
        $url = 'http://gw.api.wangpos.com/api/token?vCode='. Config::get('pos.vCode') .'&secret='.Config::get('pos.vn_secret');
        $token_data = Pos::request($url);
        if($token_data->code == 0){
            return $token_data->data->access_token;
        }else{
            return $token_data->status;
        }
    }
    //签名
    public static function Sign($data,$type = 'sha1')
    {
        //排序
        ksort($data);
        //循环组串
        $str = '';
        foreach ($data as $key => $value) {
            if($value != ''){
                $str .= $key . '=' . $value . '&';
            }
        }
        //生成sgin
//        $sign = strtoupper(sha1($str . 'token=anhui-tech'));
        if($type == 'md5'){
            $sign = md5($str . 'key=' . Config::get('pos.signkey'));
        }else{
            $sign = sha1($str . 'token=' . Config::get('pos.token'));
        }

        return $sign;
    }
    //签名
    public static function financeSign($data)
    {
        //排序
        ksort($data);
        //循环组串
        $str = '';
        foreach ($data as $key => $value) {
            if($value != ''){
                $str .= $key . $value;
            }
        }
        //生成sgin
        $sign = sha1(Config::get('pos.vn_secret') . $str . Config::get('pos.vn_secret'));

        return $sign;
    }

    //验签
    public static function Verify($data, $sign)
    {

        $mySign = Pos::Sign($data);
        //字符串比较
        if (strcasecmp($mySign, $sign) == 0) {
            return true;
        } else {
            return false;
        }
    }

    public static function array_remove($data, $key){
        if(!array_key_exists($key, $data)){
            return $data;
        }
        $keys = array_keys($data);
        $index = array_search($key, $keys);
        if($index !== FALSE){
            array_splice($data, $index, 1);
        }
        return $data;

    }

}
